package site.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import site.entity.User;
import site.model.UserDao;

import javax.persistence.EntityNotFoundException;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    protected Logger log = LoggerFactory.getLogger(this.getClass());


    @Qualifier("userDao")
    @Autowired
    private UserDao userDao;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException, DataAccessException {
        try {
            log.info("Trying to login with " + username);
            return userDao.getUserByUsername(username);
        } catch (EntityNotFoundException e) {
            throw new UsernameNotFoundException("Cannot find user with name " + username);
        }
    }


    @Transactional
    public List getAllUsers() {
        return userDao.getAllAdmins();
    }


    @Transactional
    public void deleteUserById(Integer id) {
        userDao.delete(id);
    }

    @Transactional
    public void createUser(User user) {
        userDao.create(user);
    }
}
